package com.tedu.servlet;

import com.tedu.entity.User;
import com.tedu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//将创建的对象放在容器中
//value 就是访问的路径
@WebServlet(name = "LoginServlet",value = "/user/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request,
                           HttpServletResponse response)
            throws ServletException, IOException {
        // 1. 接收前端页面的数据
        //解决中文乱码问题
        request.setCharacterEncoding("utf-8");
        //获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 2. 调用业务逻辑处理
        UserServiceImpl userService = new UserServiceImpl();
        User user = new User().setUsername(username).setPassword(password);
        User user1 = userService.loginUser(user);

        // 3. 跳转
        if(user1 == null){
            // 用户名或密码错误
            request.setAttribute("message", "用户名或密码错误");

            // 请求转发
            request.getRequestDispatcher("/ems/user/login.jsp").
                    forward(request, response);
        }else{
            //创建Session对象 并将用户的信息放在session作用域中
            request.getSession().setAttribute("user",user1);
            //重定向
            response.sendRedirect(request.getContextPath()+"/emp/all");
        }


    }
}
